let http = require('http');
let crypto = require('crypto');
var spawn = require('child_process').spawn;
let sendMail = require('./sendMail');
let accessUrlMap = require('./access-url-map.json');
const SECRET = '123456';
function sign(data) {
    return 'sha1=' + crypto.createHmac('sha1', SECRET).update(data).digest('hex')
}
function getFirstPath(path) {

    const match = path.match(/(.*?)\//);
    const beforeSlash = match ? match[1] : ''; // 使用正则表达式匹配直到第一个斜杠
    return beforeSlash;
    // const path = "daily-hot-api/Dockerfile";
    // console.log(beforeSlash); // 输出: daily-hot-api
}
let server = http.createServer(function (req, res) {
    console.log(req.method, req.url);
    if (req.url == '/webhook' && req.method == 'POST') {
        let buffers = [];
        req.on('data', function (data) {
            buffers.push(data);
        });
        req.on('end', function () {
            let body = Buffer.concat(buffers);
            let sig = req.headers['x-gitee-token'];
            let event = req.headers['x-gitee-event'];
            let payload = JSON.parse(body);
            console.log("触发事件:req.on.end", `${payload.repository.name}`, `${payload.repository.name}`, sig, event);
            console.log("触发事件:req.on.end", accessUrlMap, `${accessUrlMap[payload.repository.name]}`);
            let id = req.headers['x-github-delivery'];
            if (sig !== SECRET) {
                console.log("未通过校验",);
                return res.end('Not Allowed');
            }
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({ "ok": true }));

            if (event === 'Push Hook') {
                let payload = JSON.parse(body);
                // let shfilepath = "./" + getFirstPath(payload.commits[0].modified[0]) + ".sh";
                // let shfilepath = "./daily-hot-master.sh";
                let child = spawn('sh', [`./${payload.repository.name}.sh`]);
                // let child = spawn('bash', [`${shfilepath}`]);
                // let child = spawn('sh', [`./${shfilepath}.sh`]);

                let buffers = [];
                child.stdout.on('data', function (buffer) { buffers.push(buffer) });
                child.stdout.on('end', function () {
                    let logs = Buffer.concat(buffers).toString();
                    console.log("执行结果:", logs);
                    sendMail(`
                        <h1>部署日期: ${new Date()}</h1>
                        <h2>部署人: ${payload.pusher.name}</h2>
                        <h2>部署邮箱: ${payload.pusher.email}</h2>
                        <h2>提交信息: ${payload.head_commit && payload.head_commit['message']}</h2>
                        <h2>访问地址: ${accessUrlMap[payload.repository.name]}</h2>
                        <h2>布署日志: 详见deploy附件</h2>
                    `, logs);
                });
                //   <h2>布署日志: ${logs.replace("\r\n", '<br/>')}</h2>
                child.on('close', (code) => {
                    console.log(`子进程退出，退出码 ${code}`);
                });
            }

        });
        req.on('error', function (err) {
            console.error('Request error:', err);
            res.end('Error');
        });

    } else {
        res.end('Now Found!');
    }
});
server.listen(4000, () => {
    console.log('服务正在4000端口上启动!');
});
